package cn.mjnxin.iot.client.test;

import cn.mjnxin.iot.base.domain.ChannelData;
import cn.mjnxin.iot.base.domain.SocketData;
import cn.mjnxin.iot.base.util.CommonUtil;
import cn.mjnxin.iot.base.util.MixUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 编码器 将对象 编码成字节数组 --->目的地是网关
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class Terminal2GateEncoder extends MessageToByteEncoder<ChannelData> {

	@Override
	protected void encode(ChannelHandlerContext ctx, ChannelData msg, ByteBuf out) throws Exception {
		try {
			SocketData data = msg.getSocketData();
			// --------------------------
			data.getByteBuf().readerIndex(0);
			byte[] dst = new byte[data.getByteBuf().readableBytes()];
			data.getByteBuf().readBytes(dst);
			System.out.println("模拟终端发送数据：" + MixUtil.bytes2hex(dst));
			data.getByteBuf().readerIndex(0);
			// --------------------------
			out.writeBytes(data.getByteBuf());
		} finally {
			CommonUtil.releaseData(msg);
		}
	}
}
